// Fill out your copyright notice in the Description page of Project Settings.


#include "Group/WidgetGroupManager.h"
#include "Blueprint/WidgetBlueprintLibrary.h"
#include "Group/WidgetGroupLibrary.h"
#include "WGIUserWidget.h"

DEFINE_LOG_CATEGORY(WGI_WidgetGroupManagerLog);

void UWidgetGroupManager::AddWidget(UWGI_UserWidget* inWidget)
{
	if (!IsValid(inWidget))
	{
		UE_LOG(WGI_WidgetGroupManagerLog, Warning, TEXT("An invalid Widget was added . --- %s"), *inWidget->GetName());
		return;
	}
	if (OpenedWidgets.Contains(inWidget))
	{
		UE_LOG(WGI_WidgetGroupManagerLog, Warning, TEXT("The Widget has been added . --- %s"), *inWidget->GetName());
		return;
	}

	inWidget->AddToViewport();
	OpenedWidgets.Add(inWidget);
	if (IsValid(OwnerPlayer))
	{
		inWidget->SetUserFocus(OwnerPlayer);
	}
	else
	{
		OwnerPlayer = inWidget->GetOwningPlayer();
		OwnerPlayer->bShowMouseCursor = true;
		UWidgetBlueprintLibrary::SetInputMode_UIOnlyEx(OwnerPlayer, inWidget, EMouseLockMode::LockAlways);
	}
}

void UWidgetGroupManager::RemoveWidget(UWGI_UserWidget* inWidget)
{
	if (!IsValid(inWidget))
	{
		UE_LOG(WGI_WidgetGroupManagerLog, Warning, TEXT("Cannot remove an invalid UI . --- %s"), *inWidget->GetName());
		return;
	}
	if (!OpenedWidgets.Contains(inWidget))
	{
		UE_LOG(WGI_WidgetGroupManagerLog, Warning, TEXT("This UI is not added to the widget group . --- %s"), *inWidget->GetName());
		//return;
	}

	OpenedWidgets.RemoveSingle(inWidget);
	inWidget->RemoveFromParent();
	if (OpenedWidgets.IsValidIndex(0))
	{
		OpenedWidgets.Last()->SetUserFocus(OwnerPlayer);
	}
	else
	{
		WidgetGroupLibrary::ClearWidgetGroupManager();
	}
}

void UWidgetGroupManager::RemvoeLastWidget(bool bUpdateFoucs /*= true*/)
{
	if (OpenedWidgets.IsValidIndex(0))
	{
		OpenedWidgets.RemoveAt(OpenedWidgets.Num() - 1);
		OpenedWidgets.Last()->RemoveFromParent();
	}

	if (bUpdateFoucs)
	{
		if (OpenedWidgets.IsValidIndex(0))
		{
			OpenedWidgets.Last()->SetUserFocus(OwnerPlayer);
		}
		else
		{
			WidgetGroupLibrary::ClearWidgetGroupManager();
		}
	}
}

void UWidgetGroupManager::ClearWidget()
{
	for (size_t i = 0; i < OpenedWidgets.Num(); i++)
	{
		if (IsValid(OpenedWidgets[i]))
		{
			OpenedWidgets[i]->RemoveFromParent();
		}
	}
	OpenedWidgets.Empty();

	if (IsValid(OwnerPlayer))
	{
		OwnerPlayer->bShowMouseCursor = false;
		UWidgetBlueprintLibrary::SetInputMode_GameOnly(OwnerPlayer);
	}

	OwnerPlayer = nullptr;
	UE_LOG(WGI_WidgetGroupManagerLog, Log, TEXT("ClearGroup"));
}

#if WITH_EDITOR
void UWidgetGroupManager::GameIsEnd(UWGI_UserWidget* inWidget)
{
	if (OpenedWidgets.Contains(inWidget))
	{
		OwnerPlayer = nullptr;
		OpenedWidgets.Remove(inWidget);
	}
}
#endif
